package com.googlecode.agileplugins.settings;

import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.impl.ComponentManagerImpl;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectManagerEx;

import java.lang.reflect.Field;
import java.util.Map;

public class SettingsSharerPlugin implements ApplicationComponent {
    private ProjectManagerEx projectManagerEx;

    public SettingsSharerPlugin() {
    }

    public void initComponent() {
        projectManagerEx = ProjectManagerEx.getInstanceEx();
        replaceComponent(ProjectManager.class, new SettingsCheckerProjectManagerEx(projectManagerEx));
        ProjectManagerEx projectManagerEx1 = ProjectManagerEx.getInstanceEx();
        System.out.println("Project manager replaced with " + projectManagerEx1.getClass());
    }

    public void disposeComponent() {
        replaceComponent(ProjectManager.class, projectManagerEx);
    }

    public String getComponentName() {
        return "SettingsSharerPlugin";
    }

    private void replaceComponent(Class iface, Object implementation) {
        Application application = ApplicationManager.getApplication();
        try {
            Field field = ComponentManagerImpl.class.getDeclaredField("j");
            field.setAccessible(true);
            Map map = (Map) field.get(application);
            map.put(iface, implementation);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
